<template>
  <h2>Please enter your username and password.</h2>
  <el-form :label-position="labelPosition" label-width="auto" :model="formLabelAlign" style="max-width: 600px">
    <el-form-item label="Username" :label-position="itemLabelPosition">
      <el-input v-model="formLabelAlign.username" size="large" />
    </el-form-item>
    <el-form-item label="Password" :label-position="itemLabelPosition">
      <el-input v-model="formLabelAlign.password" size="large" />
    </el-form-item>
    <el-form-item label="Verity" :label-position="itemLabelPosition">
      <div class="verify-code-container">
        <el-input v-model="formLabelAlign.checkcode" size="large" style="width: 200px" />
        <canvas ref="verifyCanvas" @click="refreshVerifyCode" class="verify-code-canvas"></canvas>
      </div>
    </el-form-item>
  </el-form>
  <div>
    <el-button type="primary" size="large" @click="handleLogin">Login</el-button>
    <div class="third-party-login">
      <span>Or login with:</span>
      <el-button type="success" size="large" @click="handleGiteeLogin" class="gitee-login-btn">
        <img src="https://gitee.com/static/images/logo-black.svg?t=158106664" alt="Gitee" class="gitee-icon" />
      </el-button>
      <el-button type="primary" size="large" @click="handleGithubLogin" class="github-login-btn">
        <img src="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png" alt="GitHub" class="github-icon" />
      </el-button>
    </div>
    <div class="registerDiv">
      <span>Need a username and password?</span>
      <button @click="toRegister" class="registerButton">Register Now!</button>
    </div>
  </div>
</template>

<script lang="ts" setup>
// 导入所需的 Vue 组件和路由
import { reactive, ref, onMounted, onBeforeMount, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
// 导入自定义的网络请求模块
import apiClient from '@/api/api'
// 导入store
import store from '@/store'

// 初始化路由实例
const router = useRouter()
const verifyCanvas = ref<HTMLCanvasElement | null>(null)
const verifyCode = ref('')
// 生成随机验证码
const generateVerifyCode = () => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let code = ''
  for (let i = 0; i < 4; i++) {
    code += chars[Math.floor(Math.random() * chars.length)]
  }
  verifyCode.value = code
  return code
}

// 绘制验证码
const drawVerifyCode = () => {
  const canvas = verifyCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  if (!ctx) return

  // 设置画布大小
  canvas.width = 100
  canvas.height = 40

  // 填充背景
  ctx.fillStyle = '#f0f0f0'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  // 生成新验证码
  const code = generateVerifyCode()

  // 绘制文字
  ctx.font = 'bold 24px Arial'
  ctx.textBaseline = 'middle'
  for (let i = 0; i < code.length; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 100})`
    ctx.fillText(code[i], 20 + i * 20, canvas.height / 2)
  }

  // 绘制干扰线
  for (let i = 0; i < 4; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
    ctx.beginPath()
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.stroke()
  }
}

// 刷新验证码
const refreshVerifyCode = () => {
  drawVerifyCode()
}

// 组件挂载时初始化验证码
onMounted(() => {
  drawVerifyCode()
})

// 设置表单标签的位置
const labelPosition = ref('left')
const itemLabelPosition = ref('left')
// 创建响应式表单数据对象
const formLabelAlign = reactive({
  username: '', // 用户名
  password: '', // 密码
  checkcode: '', // 验证码
})

// 处理登录逻辑的函数
const handleLogin = async () => {
  // 验证用户名和密码是否为空
  if (formLabelAlign.username.trim() === '' || formLabelAlign.password.trim() === '') {
    ElMessage({
      message: 'Please enter your username and password.',
      type: 'warning'
    })
    return
  }
  if (formLabelAlign.checkcode.trim() === '') {
    ElMessage({
      message: 'Please enter the verification code.',
      type: 'warning'
    })
    return
  }
  // 验证验证码是否正确
  if (formLabelAlign.checkcode.toLowerCase() !== verifyCode.value.toLowerCase()) {
    ElMessage({
      message: 'Verification code is incorrect.',
      type: 'error'
    })
    refreshVerifyCode()
    return
  }
  try {
    //发送登录请求
    await apiClient.post(`/tokens?username=${formLabelAlign.username}&&password=${formLabelAlign.password}`).then((response) => {
      if (response.data.status !== 0) {
        ElMessage({
          message: response.data.message,
          type: 'error'
        })
        refreshVerifyCode()
        return
      } else {
        // 登录成功
        ElMessage({
          message: 'Login successful!',
          type: 'success'
        })
        localStorage.setItem('token', response.data.data)
        // 将是否登录的状态设置为true
        store.commit('setLoginStatus', true)
        router.push('/home')
      }
    })
  } catch (error) {
    ElMessage({
      message: 'Login failed. Please try again.',
      type: 'error'
    })
  } finally {
    refreshVerifyCode()
  }

}

// 处理注册跳转的函数
const toRegister = () => {
  // 跳转到注册页面
  router.push('/register')
}
// OAuth授权URL
const GITEE_AUTHORIZE_URL = "http://localhost:8091/oauth/renderGitee"
const GITHUB_AUTHORIZE_URL = "http://localhost:8091/oauth/renderGithub"

// 处理Gitee登录
const handleGiteeLogin = () => {
  // 重定向到Gitee授权页面
  window.location.href = GITEE_AUTHORIZE_URL
}

// 处理GitHub登录
const handleGithubLogin = () => {
  // 重定向到GitHub授权页面
  window.location.href = GITHUB_AUTHORIZE_URL
}


</script>
<style scoped>
.el-form {
  margin-top: 5%;
}

.el-form .el-form-item {
  margin-bottom: 30px;
}

.el-input {
  width: 300px;
}

.el-input__inner {
  height: 45px !important;
  font-size: 16px !important;
  padding: 0 15px !important;
}

.el-button {
  margin-top: 5%;
  width: 300px;
  height: 45px;
  font-size: 16px;
}

.third-party-login {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.third-party-login span {
  margin-bottom: 10px;
  color: #606266;
}

.gitee-login-btn {
  margin-top: 10px;
  background-color: #4fc08d;
  border-color: #4fc08d;
}

.gitee-icon{
  width: 80px;
  height: 80px;
}
.github-icon{
  width: 40px;
  height: 40px;
}
.github-login-btn {
  margin-top: 10px;
  margin-left: 0px;
  background-color: #24292e;
  border-color: #24292e;
}

.registerDiv {
  margin-top: 2%;
  margin-bottom: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  z-index: 1;
}

.registerButton {
  border: none;
  background: none;
  color: #007bff;
  font-size: larger;
  cursor: pointer;
}

.verify-code-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.verify-code-canvas {
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}


</style>